/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { useEffect, useState, useCallback, useRef } from 'react';
import { Spin } from 'antd';
import { history } from 'umi';
import styles from './index.less';

/**
 * @param {string} type news|adv，区分是广告还是新闻
 * @param {string} width 宽
 * @param {string} height 高
 * @param {string} position left|center|right 位置
 * @param {string} detailPath 新闻详情页路由
 * @param {string} direction 轮播图滚动方向（horizontal，vertical)
 */
const Advertisement = ({
  type,
  width,
  height,
  position,
  detailPath,
  style,
  advType = '1',
  direction = 'vertical',
}: {
  type: string;
  width: string;
  height: string;
  position: string;
  detailPath: string;
  style: object;
  advType: string;
  direction: string;
}) => {
  const [loading, setLoading] = useState(true);
  const [platform, setPlatform] = useState('jdkWeb');
  const [show, setShow] = useState(true);
  const iframeRef = useRef<any>(null);

  useEffect(() => {
    // eslint-disable-next-line no-restricted-globals
    if (location.hostname.match('kuaidihelp.com')) {
      // 降域解决iframe跨域问题
      document.domain = 'kuaidihelp.com';
      if (type == 'news') {
        setPlatform('jdkWeb_news');
        history.push(`${detailPath}`);
      }
    } else {
      setShow(true);
    }
  }, [type]);

  const onload = useCallback(() => {
    try {
      if (iframeRef?.current?.height == 0) {
        iframeRef.current.height = 0;
      }
      setLoading(false);
    } catch (error) {
      setShow(false);
      console.warn(error);
    }
  }, [type]);

  return (
    <div className={styles[position]} style={style}>
      {show && (
        <Spin spinning={loading}>
          <iframe
            title='adv'
            ref={iframeRef}
            width={width}
            onLoad={onload}
            src={`//m.kuaidihelp.com/adv_news/advandnews?type=${type}&platform=${platform}&position=${advType}&width=${width}&height=${height}&detailPath=${detailPath}&direction=${direction}`}
            scrolling='no'
          />
        </Spin>
      )}
    </div>
  );
};
export default Advertisement;
